package com.lcb.manager.web;

import com.alibaba.fastjson.JSON;
import com.lcb.manager.configuration.Config;
import com.lcb.manager.entity.Address;
import com.lcb.manager.repository.AddressRepository;
import com.lcb.manager.util.MediaUploadUtil;
import com.lcb.manager.vo.*;
import com.lcb.manager.entity.News;
import com.lcb.manager.repository.NewsRepository;
import com.lcb.manager.util.RandomUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.sql.Date;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Controller
@RequestMapping("/news")
public class NewsController {

    @Autowired
    private NewsRepository newsRepository;

    @Autowired
    private AddressRepository addressRepository;

    @RequestMapping(value = "/")
    public String index() {
        return "news";
    }

    @ResponseBody
    @RequestMapping(value = "/get", method = RequestMethod.GET)
    public String getNewsInfo() {
        List<News> newsList = newsRepository.findAll();
        List<NewsVo> newsVoList = newsList.stream().map(NewsVo::fromEntity).collect(Collectors.toList());

        return JSON.toJSONString(newsVoList);
    }

    @ResponseBody
    @PostMapping("/add")
    public String add(@RequestParam("files") MultipartFile[] files,
                      @RequestParam("type") int type,
                      @RequestParam("date") String date,
                      @RequestParam("title") String title,
                      @RequestParam("content") String content) throws IOException {
        Json result = new Json();
        int fileLen = files.length;
        if (date.isEmpty() || title.isEmpty() || content.isEmpty()) {
            result.code = 1;
            result.msg = "请勿提交空数据！";
            return JSON.toJSONString(result);
        } else if (fileLen == 0) {
            result.code = 1;
            result.msg = "请选择图片！";
            return JSON.toJSONString(result);
        } else {
            News news = new News();
            news.setDate(Date.valueOf(date));
            news.setTitle(title);
            news.setContent(content);
            news.setType(type);
            if (type == 1) {
                List<String> imageNameList = MediaUploadUtil.uploadImages(files);
                news.setPictures(JSON.toJSONString(imageNameList));
            } else {
                String videoName = MediaUploadUtil.uploadVideo(files);
                news.setVideo(videoName);
            }
            newsRepository.save(news);
            result.code = 0;
            result.msg = "提交成功！";
            return JSON.toJSONString(result);
        }
    }

    @ResponseBody
    @PostMapping("/edit")
    public String edit(@RequestParam("files") MultipartFile[] files,
                       @RequestParam("type") int type,
                       @RequestParam("id") int id,
                       @RequestParam("date") String date,
                       @RequestParam("title") String title,
                       @RequestParam("content") String content,
                       RedirectAttributes redirectAttributes) throws IOException {
        Json result = new Json();

        int fileLen = files.length;
        if (date.isEmpty() || title.isEmpty() || content.isEmpty()) {
            result.code = 1;
            result.msg = "请勿提交空数据！";
            return JSON.toJSONString(result);
        } else if (fileLen == 0) {
            result.code = 1;
            result.msg = "请选择图片！";
            return JSON.toJSONString(result);
        } else {
            News news = newsRepository.findById(id).orElse(null);
            if (news != null) {
                news.setDate(Date.valueOf(date));
                news.setTitle(title);
                news.setContent(content);
                news.setType(type);
                if (type == 1) {
                    List<String> imageNameList = MediaUploadUtil.uploadImages(files);
                    news.setPictures(JSON.toJSONString(imageNameList));
                } else {
                    String videoName = MediaUploadUtil.uploadVideo(files);
                    news.setVideo(videoName);
                }
                newsRepository.save(news);
            }
            result.code = 0;
            result.msg = "提交成功！";
            return JSON.toJSONString(result);
        }
    }

    @ResponseBody
    @RequestMapping(value = "/delete")
    public String delete(@RequestParam int id) {
        Json result = new Json();
        newsRepository.deleteById(id);
        result.code = 0;
        result.msg = "删除成功！";
        return JSON.toJSONString(result);
    }

    @ResponseBody
    @RequestMapping(value = "/list")
    public String getNewsList(@RequestParam(defaultValue = "") String date, @RequestParam int page, @RequestParam int limit) {
        Json result = new Json();
        Pageable pageable = PageRequest.of(page - 1, limit);
        Page<News> pageResult;
        if (!date.isEmpty()) {
            String year = date.split("-")[0];
            String month = date.split("-")[1];
            pageResult = newsRepository.findByDateOrderByDateAsc(year, month, pageable);
        } else {
            pageResult = newsRepository.findByOrderByDateAsc(pageable);
        }
        result.code = 0;
        result.count = (int) pageResult.getTotalElements();
        result.data = pageResult.getContent();
        return JSON.toJSONStringWithDateFormat(result, "yyyy-MM-dd");
    }

    @RequestMapping(value = "/get_empty")
    public String getEmpty(ModelMap modelMap) {
        modelMap.put("title", "企业新闻输入");
        modelMap.put("isEdit", false);
        return "_content";
    }

    @RequestMapping(value = "/get_one")
    public String getOne(ModelMap modelMap, @RequestParam int id) {
        News news = newsRepository.findById(id).orElse(null);
        NewsVo vo = NewsVo.fromEntity(news);
        modelMap.put("title", "企业新闻输入");
        modelMap.put("isEdit", true);
        if (vo != null) {
            modelMap.put("vo", vo);
        }
        return "_content";
    }

    @RequestMapping(value = "/address")
    public String address(ModelMap modelMap) {
        Address address = addressRepository.findById(1).orElse(null);
        modelMap.put("title", "致辞定版输入");
        if (address != null) {
            AddressVo vo = AddressVo.fromEntity(address);
            modelMap.put("isEdit", true);
            modelMap.put("vo", vo);
        } else {
            modelMap.put("isEdit", false);
        }
        return "_address";
    }

    @ResponseBody
    @PostMapping("/edit_address")
    public String edit_address(@RequestParam("files") MultipartFile[] files,
                               @RequestParam("display_address") boolean displayAddress,
                               @RequestParam("text") String text) throws IOException {
        Json result = new Json();

        int fileLen = files.length;
        if (text.isEmpty()) {
            result.code = 1;
            result.msg = "请勿提交空数据！";
            return JSON.toJSONString(result);
        } else {
            Address address = addressRepository.findById(1).orElse(null);
            List<String> imageNameList = MediaUploadUtil.uploadImages(files);
            if (address == null) {
                address = new Address();
                address.setId(1);
            }
            address.setDisplayAddress(displayAddress);
            address.setText(text);
            address.setPictures(JSON.toJSONString(imageNameList));
            addressRepository.save(address);
            result.code = 0;
            result.msg = "提交成功！";
            return JSON.toJSONString(result);
        }
    }
}